<style lang="scss">
.tablelist-searchs {
    padding: 10px 10px 0;
    background-color: #fff;
    border: 1px solid #ddd;
    margin-bottom: 10px;
    border-radius: 8px;
    .vview-formitem {
        margin-bottom: 10px;
    }
}
</style>
<style lang="scss" scoped>
.show-search-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .search-show-item {
        position: relative;
        cursor: pointer;
        line-height: 32px;
        height: 32px;
        border: 1px solid rgba(0, 110, 255, 0.6);
        border-radius: 2px;
        background: rgba(0, 110, 255, 0.04);
        margin-right: 15px;
        padding-left: 10px;
        padding-right: 5px;
        margin-bottom: 10px;
        &-tooltip-item {
            padding: 2px 0;
        }
        &-label {
            padding-right: 5px;
        }
        &-close-icon {
            font-size: 16px;
            color: #9da6be;
            cursor: pointer;
            &:hover {
                color: #4c505b;
            }
        }
    }
}
</style>
<template>
    <div>
        <Form
            v-bind="getFormProps"
            class="tablelist-searchs clearfix"
            @submit.prevent="search('search')"
            @keydown.enter="enterSearch"
        >
            <slot name="header"></slot>
            <div v-if="data.length" :class="getPullAlign">
                <template :key="item.key" v-for="item in getVisibleChild">
                    <FormItem
                        style="margin-bottom: 10px;"
                        labelWidth="90"
                        v-bind="getFormItemProps(item)"
                    >
                        <compRenderfn
                            v-bind="getFormChildData(item)"
                        ></compRenderfn>
                    </FormItem>
                </template>
                <div class="inline-block margin-bottom-10">
                    <slot :search="search">
                        <Button
                            class="margin-left-5"
                            type="primary"
                            icon="md-search"
                            @click="search('search')"
                            >{{ $ct("global.common.search") }}</Button
                        >
                        <Button
                            class="margin-left-5"
                            icon="md-refresh"
                            @click="search('reset')"
                            >{{ $ct("global.common.reset") }}</Button
                        >
                        <Button
                            v-if="showMoreSearchs"
                            class="margin-left-5"
                            type="dashed"
                            @click="search('more')"
                        >
                            {{ $ct("global.common.searchs") }}&nbsp;
                            <!-- <vIcon type="ios-arrow-down"></vIcon> -->
                            <Icon type="md-arrow-dropdown" />
                        </Button>
                    </slot>
                    <slot name="searchButton"></slot>
                </div>
            </div>
            <Transition>
                <div v-if="show" style="width: 100%" class="clearfix pull-left">
                    <FormItem
                        v-for="item in getOtherChild"
                        :key="item.key"
                        style="margin-bottom: 10px;"
                        v-bind="getFormItemProps(item)"
                    >
                        <compRenderfn
                            v-bind="getFormChildData(item)"
                        ></compRenderfn>
                    </FormItem>
                </div>
            </Transition>
        </Form>
        <div class="show-search-list">
            <div
                v-for="(item, index) in dataArray"
                :key="item.key"
                class="search-show-item"
            >

                <Tooltip theme="light" :disabled="!item.showMore">
                    <template #content>
                        <div v-if="item.showMore">
                            <p class="search-show-item-tooltip-item" v-for="labelItem in item.showLabelArray" :key="labelItem.key">{{labelItem.label}}</p>
                        </div>
                    </template>
                    <span class="search-show-item-title">{{ item.label }}:</span>
                    <span
                        class="search-show-item-label"
                        v-if="Array.isArray(item.showLabel)"
                    >
                        <span
                            class="search-show-item-label-item"
                            v-for="showLabelItem in item.showLabel"
                            :key="showLabelItem.value"
                        >
                            {{ showLabelItem.label }}
                        </span>
                    </span>
                    <span class="search-show-item-label" v-else>
                        <span>{{ item.showLabel }}</span>
                    </span>
                </Tooltip>
                <Icon
                    class="search-show-item-close-icon"
                    type="ios-close"
                    @click="closeSearchItem(index)"
                />
            </div>
        </div>
    </div>
</template>


<script>
import compRenderfn from "./renderfn";
export default {
    components: {
        compRenderfn,
    },
    props: {
        data: {
            type: Array,
            default() {
                return [];
            },
        },
        align: {
            type: String,
            default: "right", //right,left
        },
    },
    data() {
        return {
            formData: {},
            baseData: {},
            show: false,
            dataArray: [],
        };
    },
    created() {
        this.formData = this.initformData();
        this.__extractCycle();
    },
    mounted() {
        // console.log('mounted')
        this.__mounted.forEach((item) => {
            item.call(this);
        });
        setTimeout(() => {
            this.search();
        }, 300);
        this.$bus.on("changelang", val=>{
            setTimeout(()=>{
                this.search('search');
            },600)
        });
        // console.log(this)
    },
    beforeUnmount() {
        this.__beforeDestroy.forEach((item) => {
            item.call(this);
        });
    },
    computed: {
        getPullAlign() {
            return `pull-${this.align || "right"}`;
        },
        getFormProps() {
            return {
                inline: true,
                ...this.$attrs,
            };
        },
        getVisibleChild() {
            return this.data.filter(function (child) {
                return child.show && !child.hidden;
            });
        },
        getOtherChild() {
            return this.data.filter(function (child) {
                return !(child.show || child.hidden);
            });
        },
        showMoreSearchs() {
            return this.data.some(function (item) {
                return !item.show;
            });
        },
    },
    methods: {
        // 点击更多搜索
        async changeSearch() {
            await this.$nextTick();
            this.$emit("on-change-search");
        },
        getFormItemProps(item) {
            let { label, props, ...other } = item;
            let { placeholder, ...otherProps } = other;
            let result = {};
            // 是否展示label
            if (item.showLabel) {
                result = {
                    label: item.langKey
                    ? this.$ct(item.langKey, { defaultValue: item.label })
                    : item.label,
                    ...item.formItem,
                };
                if (item.labelWidth) {
                    // 根据label长度自动判断labelWidth功能待后续开发
                    result.labelWidth = item.labelWidth;
                }
            }
            else {
                result = {
                    ...item.formItem,
                    labelWidth: 0
                };
            }
            return result;
            // return {
            //     label: item.langKey
            //         ? this.$t(item.langKey, { defaultValue: item.label })
            //         : item.label,
            //     ...item.formItem,
            // };
        },
        getFormChildData(item) {
            let {
                tag,
                props,
                scopedSlots = {},
                key,
                type,
                style,
                on = {},
                nativeOn = {},
                children,
                options,
                removeInput
            } = item;
            // 是否展示label
            if (item.showLabel) {
                props = Object.assign(
                    { clearable: true, dropStyle: "width:auto;min-width:96px;" },
                    props,
                    { modelValue: this.formData[key] }
                );
            }
            else {
                props = Object.assign(
                    { clearable: true, dropStyle: "width:auto;min-width:96px;" },
                    { placeholder: item.langKey
                        ? this.$ct(item.langKey, { defaultValue: item.label })
                        : item.label,
                    ...item.formItem, },
                    props,
                    { modelValue: this.formData[key] },
                );
            }
            Object.keys({...on}).forEach(item => {
                let eventName = item.replace('on-', '');
                on[`on${eventName[0].toUpperCase()}${eventName.slice(1, eventName.length)}`] = on[item].bind(this);
			});
            if (!on.onInput && !removeInput) {
                // on.input = (val) => {
                //     this.$set(this.formData, key, val);
                // };
                on["onUpdate:modelValue"] = val => this.formData[key] = val;
            }
            // console.log(tag)
            if (tag == "Select") {
                if (options instanceof Array) {
                    children = (h) => {
                        return options.map((item) => {
                            if (item === null || typeof item !== "object") {
                                item = { value: item, label: item };
                            }
                            // return h("Option", {
                            //     // attrs: { ...item },
                            //     // domProps: { innerHTML: item.label },
                            //     ...item,
                            //     innerHTML: item.label
                            // });
                            return <Option innerHTML={item.label} value={item.value} key={item.value}>{item.label}</Option>
                        });
                    };
                }
            } else {
                if (options instanceof Array) {
                    children = (h) => {
                        return options.map((item) => {
                            if (item === null || typeof item !== "object") {
                                item = { value: item, label: item };
                            }
                            return h("Option", {
                                attrs: { ...item, type: null },
                            });
                        });
                    };
                }
            }
            Object.keys(scopedSlots).forEach((key) => {
                scopedSlots[key] = scopedSlots[key].bind(this, h);
            });
            Object.keys(on).forEach((key) => {
                on[key] = on[key].bind(this);
            });
            Object.keys(nativeOn).forEach((key) => {
                nativeOn[key] = nativeOn[key].bind(this);
            });
            if (style && typeof style === "object") {
                style = {
                    width: "136px",
                    ...style,
                };
            } else {
                style = "width:136px;" + style;
            }
            return {
                tag,
                style,
                class: item.class,
                key,
                scopedSlots,
                ...on,
                nativeOn,
                // attrs: props,
                ...props,
                children,
            };
        },
        initformData() {
            // console.log("propsData", this.data);
            const formData = {},
                formatters = {};
            this.data.forEach((item) => {
                const { default: init, key, formatter } = item;
                if (init !== undefined) formData[key] = init;
                if (typeof formatter === "function")
                    formatters[key] = formatter;
            });
            this.__formatters = formatters;
            return formData;
        },
        search(type = "search") {
            if (type === "more") return (this.show = !this.show);
            let formdata = {};
            if (type === "reset") {
                // Object.keys(this.formData).forEach(key => {
                // 	formdata[key] = "";
                // 	this.$set(this.formData, key, "");
                // });
                this.$bus.emit("changereset", 'reset');
                formdata = null;
                this.formData = {};
            } else {
                const keys = [];
                this.data.forEach((item) => {
                    //过滤掉不显示的key
                    if (!item.hidden) keys.push(item.key);
                });
                Object.keys(this.formData).forEach((key) => {
                    if (keys.indexOf(key) == -1) {
                        formdata[key] = "";
                        return;
                    }
                    const formatter = this.__formatters[key],
                        value = this.formData[key];
                    formdata[key] = formatter ? formatter(value, key) : value;
                });
            }
            // 展示搜索item
            this.handleShowSearch(formdata);
            this.$emit("on-search", formdata);
        },
        // 展示搜索item
        handleShowSearch(formData) {
            // console.log("formData", formData);
            // console.log("propsData", this.data);
            if (!formData) return (this.dataArray = []);
            // 遍历所有当前搜索中使用的key
            let dataArray = [
                // {
                //     key: "EQ_orderNo",
                //     label: "采购单编号",
                //     on: {
                //         'on-change': () => {},
                //         'on-input': () => {}
                //     },
                //     show: true,
                //     showLabel: "131231",
                //     tag: "Input",
                //     value: "131231"
                // }
            ];
            let combineKeySet = new Set();
            Object.keys(formData).map((key) => {
                if ((!formData[key] && formData[key] !== 0) || formData[key].length === 0) return;
                this.data.map((item) => {
                    // 如果不想展示searchTip，需要在渲染设置上添加hideSearchTip = true
                    if (item.key === key && !item.hideSearchTip) {
                        // 如果需要合并，则不放入array中
                        if (item.combineKey) return combineKeySet.add(item.combineKey);
                        let newItem = {};
                        // 解决重复渲染问题，去除on字段
                        newItem = { ...item, on: {}, value: formData[key] };
                        dataArray.push(newItem);
                    }
                });
            });

            dataArray.map((item) => {

                item.showLabel = item.value;
                // 选框
                if (item.tag === "vSelect" || item.tag === "Select") {
                    // console.log(item);
                    if (Array.isArray(item.value)) {
                        item.showLabelArray = item.value.map((valueItem) => {
                            return item.options.filter((optionsItem) => {
                                return optionsItem.value === valueItem;
                            })[0];
                        });
                    } else {
                        // console.log('单选', item);
                        return item.showLabel = item.options.filter(optionsItem => {
                            return item.value === optionsItem.value
                        })[0].label;
                        // return item.showLabel = item.value;
                    }
                    item.showLabel = "";
                    if (item.showLabelArray.length > 2) {
                        for (let i = 0; i < 2; i++) {
                            item.showLabel +=
                                item.showLabelArray[i].label + " ";
                        }
                        item.showLabel += `等${item.showLabelArray.length}项`;
                        item.showMore = true;
                    } else {
                        item.showLabel = item.showLabelArray;
                    }
                }
                // 如果是日期选择
                if(item.tag === 'DatePicker'){
                    if(item.props.type === 'date'){
                        item.showLabel = this.handleDateFormat(item.value,'yyyy-mm-dd');
                    }else if(item.props.type === 'daterange'){
                        item.showLabel = this.handleDateFormat(item.value[0],'yyyy-mm-dd')+' ~ '+this.handleDateFormat(item.value[1],'yyyy-mm-dd');
                    }
                    else if(item.props.type === 'month'){
                        item.showLabel = this.handleDateFormat(item.value,'yy-mm');
                    }
                }
            });
            // console.log('combineKeySet', combineKeySet);
            // 合并相同的key
            for (let item of combineKeySet.keys()) {
                let keysArr = Object.keys(formData).filter(formKey => {
                    return formKey.split('_')[1] === item
                });
                let formItem = {};
                let array = []
                array = keysArr.map(sItem => {
                    return this.data.filter(dataItem => {
                        return dataItem.key === sItem
                    })[0]
                })
                formItem = {
                    ...array[0],
                    keyArray: keysArr,
                    // value: `${formData[array[0].key]}~${formData[array[1].key]}`,
                    showLabel: `${formData[array[0].key]}~${formData[array[1].key]}`
                }
                // console.log('formItem', formItem);
                dataArray.push(formItem);
            }
            // console.log('dataArray', dataArray);
            this.dataArray = dataArray;
        },
        closeSearchItem(index) {
            if (this.dataArray[index].keyArray) {
                this.dataArray[index].keyArray.map(item => {
                    this.formData[item] = "";
                })
            }
            else {
                this.formData[this.dataArray[index].key] = "";
            }
            this.dataArray.splice(index, 1);
            this.$bus.emit("changereset", 'deleteItem');
            this.$emit("on-search", this.formData);
        },
        //enter键自动搜索
        enterSearch() {
            // if (!this.$attrs.isEnterSearch) return;
            // this.search("search");
            // 优化单form回车自动提交的问题
            // console.log(this.$attrs.isEnterSearch)
            if (this.$attrs.isEnterSearch === true) {
                this.search("search");
            } else return;
        },
        __extractCycle() {
            const __mounted = [],
                __beforeDestroy = [];
            this.data.forEach((item) => {
                const { created, mounted, methods, beforeDestroy, key } = item;
                if (methods) {
                    Object.keys(methods).forEach((method) => {
                        this[method] = methods[method].bind(this);
                    });
                }
                if (created) created.call(this);
                if (mounted) __mounted.push(mounted);
                if (beforeDestroy) __beforeDestroy.push(beforeDestroy);
            });
            this.__mounted = __mounted;
            this.__beforeDestroy = __beforeDestroy;
        },
    },
};
</script>



